package vip.ifmm.lehouse.email.service.helper;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.*;

/**
 * 线程池帮助类
 *
 * @author Fish
 * <p>Email: fishinlove@163.com</p>
 * <p>created by 2019/06/18 18:27:46</p>
 */
@Component
public final class ThreadHelper {

    @Value("${core-size}")
    private int coreSize = 4;

    @Value("${max-size}")
    private int maxSize = 16;

    @Value("${thread-expire}")
    private int threadExpire = 30;

    @Value("${queue-size}")
    private int queueSize = 1024;

    // 内置线程池，用来执行任务
    private ThreadPoolExecutor threadPool;

    @PostConstruct
    public void init() {
        threadPool = new ThreadPoolExecutor(
                coreSize, maxSize,
                threadExpire, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(queueSize),
                new ThreadPoolExecutor.CallerRunsPolicy() // 任务拒绝策略
        );
    }

    /** 执行任务
     *
     * @param task 要执行的任务
     */
    public void submit(Runnable task) {
        threadPool.submit(task);
    }

    /**
     * 执行任务
     *
     * @param task 要执行的任务
     * @return 返回执行结果
     */
    public Future<?> submit(Callable<?> task) {
        return threadPool.submit(task);
    }

    // 销毁工作
    @PreDestroy
    public void destroy() {
        // 关闭线程池
        threadPool.shutdown();
    }
}
